import { fetchPost } from "../../common/fetch";
import { $ } from "../../common/utils";
import { check } from "../../common/form-check";

export default (conf) => {
    const $form = $("register-info-form");
    let formValues = {};
    Array.from($form.elements).forEach((item) => {
        if (item.name){
            formValues[item.name] = item.value;
        }
    });
    $form.onsubmit = async () => {

        let checkResults = check($form);

        if (checkResults.length){
            const name = checkResults[0].name;
            const type = checkResults[0].type;
            const message = checkResults[0].message;
            if (type ==="present") {
                alert(name + message )
            } else {
                alert(message);
            }
        } else {
            let  data = await fetchPost("/register/info", formValues);
            if ( data.code === 200 ){
                conf.success && conf.success(data);
            } else {
                conf.error && conf.error(data);
            }
        }
    }
}